package com.example.erhuo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.erhuo.Good;
import com.example.erhuo.R;
import com.example.erhuo.adapter.GoodAdapter;
import com.example.erhuo.api.NetAPI;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private GoodAdapter goodAdapter;
    private ListView listView;
    private static String TAG = "SearchActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.title_layout);
            TextView textView = (TextView) actionBar.getCustomView().findViewById(R.id.display_title);
            textView.setText("查询");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        setContentView(R.layout.activity_search);
        initActivity();
        setActivity();
        Intent intent = getIntent();
        String searchKeyword = intent.getStringExtra("search");
        searchGood(searchKeyword);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initActivity() {
        goodAdapter = new GoodAdapter(new LinkedList<Good>(), SearchActivity.this);
        listView = findViewById(R.id.search_listView);
    }

    private void setActivity() {
        listView.setAdapter(goodAdapter);
        listView.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {

    }


    private void searchGood(String keyword) {
        RequestBody body = new FormBody.Builder()
                .add("goodname", keyword)
                .build();
        Callback callback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "获取商品列表失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String information = response.body().string();
                //Log.i(TAG, information);
                JSONObject json;
                try {
                    json = new JSONObject(information);
                    String code = json.getString("code");
                    switch (code) {
                        case "200": {
                            Log.i(TAG, "获取检索商品成功");
                            JSONArray dataJson = json.getJSONObject("data").getJSONArray("goods");
                            for (int i = 0; i < dataJson.length(); i++) {
                                JSONObject object = dataJson.getJSONObject(i);
                                String goodId = object.getString("goodid");
                                String goodStatus = object.getString("goodstatus");
                                String goodTitle = object.getString("goodname");
                                String goodDescription = object.getString("gooddescription");
                                String goodPrice = object.getString("goodprice");
                                String goodCategory = object.getString("goodcategory");
                                String goodSendTime = object.getString("goodsendtime");
                                String goodSenderId = object.getString("goodsenderid");
                                String goodPicUrl = null;
                                try {
                                    goodPicUrl = object.getString("imagePATH");
                                } catch (Exception e) {
                                    Log.e(TAG, "这个商品无图片");
                                }
                                Good good = new Good(goodTitle, goodPrice, goodDescription, goodCategory, goodSendTime, goodStatus, goodSenderId, goodId, goodPicUrl);
                                Callback callback = new Callback() {
                                    @Override
                                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                        good.setImage(null);
                                    }

                                    @Override
                                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                        byte[] bytes = response.body().bytes();
                                        Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                                        good.setImage(image);
                                    }
                                };
                                NetAPI.get("api/download/?path=" + goodPicUrl, callback, "");
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                goodAdapter.addGood(good);
                            }
                            Log.i(TAG, "获取了 " + dataJson.length() + " 件商品信息");
                            Log.i(TAG, "目前列表大小：" + goodAdapter.getCount());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listView.setAdapter(goodAdapter);
                                }
                            });
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        };
        NetAPI.postJson("api/GoodOper/searchGoodsWithName/", body, callback);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Log.i(TAG, "你点击了第" + position + "项");
        //Toast.makeText(SearchActivity.this, "你点击了第" + position + "项", Toast.LENGTH_SHORT).show();
        if (MainActivity.token == null || MainActivity.token.equals("")) {
            Toast.makeText(getApplicationContext(), "请登录", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(SearchActivity.this, GoodDetailActivity.class);
        Good good = (Good) goodAdapter.getItem(position);
        String goodId = good.getId();
        //intent.putExtra("good", good);
        intent.putExtra("goodId", goodId);
        startActivity(intent);
    }
}